var usertweencar = new TimelineLite({paused: true}),
usertweencarenterprise = new TimelineLite({paused: true}),
reservationtweenConfirm = new TimelineLite({paused: true}),
entrepriceTL = new TimelineLite({paused: true}),
clientTL = new TimelineLite({paused: true});
reservationtweenConfirmFinal = new TimelineLite({paused: true});
entrepriceTL.add(TweenMax.to("#div-pre-loguin", 0.5, {scale: 0}));
entrepriceTL.add(TweenMax.to("#div-pre-loguin", 0.1, {css: {display: 'none'}}));
entrepriceTL.add(TweenMax.to("#div-enterprise-form", 0.1, {scale: 0}));
entrepriceTL.add(TweenMax.to("#div-enterprise-form", 0.1, {css: {display: 'inline-block'}}));
entrepriceTL.add(TweenMax.to("#div-enterprise-form", 0.5, {scale: 1}));
clientTL.add(TweenMax.to("#div-pre-loguin", 0.5, {scale: 0}));
clientTL.add(TweenMax.to("#div-pre-loguin", 0.1, {css: {display: 'none'}}));
clientTL.add(TweenMax.to("#div-loguin-form", 0.1, {scale: 0}));
clientTL.add(TweenMax.to("#div-loguin-form", 0.1, {css: {display: 'inline-block'}}));
clientTL.add(TweenMax.to("#div-loguin-form", 0.5, {scale: 1}));
usertweencar.add(TweenMax.to("#div-user-register", 0.5, {css: {height: 0}, ease: Back.easeIn}));
usertweencar.add(TweenMax.to("#div-reservation", 0.5, {css: {height: 1790}, ease: Bounce.easeOut, delay: 0.5}));
usertweencarenterprise.add(TweenMax.to("#div-user-register", 0.5, {css: {height: 0}, ease: Back.easeIn}));
usertweencarenterprise.add(TweenMax.to("#div-reservation", 0.5, {css: {height: 2000}, ease: Bounce.easeOut, delay: 0.5}));
reservationtweenConfirm.add(TweenMax.to("#div-reservation", 0.5, {css: {height: 0}, ease: Back.easeIn}));
reservationtweenConfirm.add(TweenMax.to("#confirm-reservation", 0.5, {css: {height: 850}, ease: Bounce.easeOut, delay: 0.5}));
reservationtweenConfirmFinal.add(TweenMax.to("#confirm-reservation", 0.5, {css: {height: 0}, ease: Bounce.easeOut}));
reservationtweenConfirmFinal.add(TweenMax.to("#confirm-reservation2", 0.5, {css: {height: 130}, ease: Bounce.easeOut, delay: 0.5}));
var calculateTarifV = $("#calculateTarif").validate({
	onkeyup: false,
	messages: {
		tarifTest2: "Ce champ est obligatoire",
		tarifTest1: "Ce champ est obligatoire"
	},
	errorPlacement: function(error, element) {

		error.css("margin-left", "60px").css("margin-top", "10px");
		if (element.attr("name") === "tarifTest1") {
			error.insertAfter("#tarifTest1");
		}
		else if (element.attr("name") === "tarifTest2") {

			error.insertAfter("#tarifTest2");
		}
	}
});
var contactform = $("#contact-form").validate({
	messages: {
		name: "Ce champ est obligatoire",
		email: {
			required: "Ce champ est obligatoire",
			email: "Votre email doit avoir le format  nom@domain.com"
		}
	},
	errorPlacement: function(error, element) {

		error.css("margin-left", "42px").css("margin-top", "10px");
		if (element.attr("name") === "email") {
			error.insertAfter("#email");
		}
		else if (element.attr("name") === "content") {

			error.insertAfter("#content");
		}
	}
});
var userform = $("#user-register-form").validate({
	messages: {
		name: "Ce champ est obligatoire",
		email: {
			required: "Ce champ est obligatoire",
			email: "Votre email doit avoir le format  nom@domain.com"
		},
		sex: "Ce champ est obligatoire",
		last_name: "Ce champ est obligatoire",
		address: "Ce champ est obligatoire",
		postal_code: "Ce champ est obligatoire",
		country: "Ce champ est obligatoire",
		phone_movil: "Ce champ est obligatoire",
		postal_code: "Ce champ est obligatoire"

	}
});
var carForm = $("#car-form").validate({
	messages: {
		conductor_name: "Ce champ est obligatoire",
		carSelect: "Ce champ est obligatoire",
		mark: "Ce champ est obligatoire",
		plate: "Ce champ est obligatoire"
	},
	errorPlacement: function(error, element) {

		error.css('float', 'left').css('margin-left', '316px');
		if (element.attr("name") == "conductor_name") {

			$("#errorConductor").append(error);
		}
		else if (element.attr("name") == "carSelect") {

			error.insertAfter("#errorCar");
		}
		else {
			error.insertAfter(element);
		}
	}

});
var conductorForm = $("#conductor-form").validate({
	messages: {
		name: "Ce champ est obligatoire",
		sex: "Ce champ est obligatoire",
		last_name: "Ce champ est obligatoire",
		address: "Ce champ est obligatoire",
		postal_code: "Ce champ est obligatoire",
		phone_movil: "Ce champ est obligatoire"
	}
});
var addCarForm = $("#add-car-form").validate({
	messages: {
		mark: "Ce champ est obligatoire",
		plate: "Ce champ est obligatoire"

	}
});
var reservationForm = $("#reservation-form").validate({
	messages: {
		date_fly: "Ce champ est obligatoire",
		hour_fly: "Ce champ est obligatoire",
		destination: "Ce champ est obligatoire",
		company_fly: "Ce champ est obligatoire",
		fly_number: "Ce champ est obligatoire",
		day_date_car_in: "Ce champ est obligatoire",
		hour_car_in: "Ce champ est obligatoire",
		date_fly_back: "Ce champ est obligatoire",
		hour_fly_back: "Ce champ est obligatoire",
		destination_fly_back: "Ce champ est obligatoire",
		company_fly_back: "Ce champ est obligatoire",
		fly_number_back: "Ce champ est obligatoire",
		day_date_car_out: "Ce champ est obligatoire",
		hour_car_out: "Ce champ est obligatoire",
		destination_fly_back: "Ce champ est obligatoire",
				company_fly_back: "Ce champ est obligatoire",
				fly_number_back: "Ce champ est obligatoire",
				condition: "Ce champ est obligatoire"
	},
	errorPlacement: function(error, element) {

		if (element.attr("name") == "day_date_car_in") {
			error.insertAfter("#hour_car_in");
		}
		else if (element.attr("name") == "hour_car_in") {

			error.insertAfter("#hour_car_in").css("margin-left", "440px");
		}
		else if (element.attr("name") == "date_fly") {

			error.insertAfter("#hour_fly");
		}
		else if (element.attr("name") == "hour_fly") {
			error.insertAfter("#hour_fly").css("margin-left", "440px");
		}
		else if (element.attr("name") == "day_date_car_out") {
			error.insertAfter("#hour_car_out");
		}
		else if (element.attr("name") == "hour_car_out") {
			error.insertAfter("#hour_car_out").css("margin-left", "440px");
		}
		else if (element.attr("name") == "date_fly_back") {
			error.insertAfter("#hour_fly_back");
		}
		else if (element.attr("name") == "hour_fly_back") {
			error.insertAfter("#hour_fly_back").css("margin-left", "440px");
		}
		else if (element.attr("name") == "condition") {
			error.insertAfter("#conditionText").css("margin-left", "60px");
		}
		else {
			error.insertAfter(element);
		}
	}
});
var loguinFormValidate = $("#loguin-form").validate({
	focusCleanup: true,
	rules: {
		phone_movil_loguin: {
			required: true
		},
		email: {
			required: true,
			email: true
		}
	},
	messages: {
		phone_movil_loguin: {
			required: "Ce champ est obligatoire"
		},
		email: {
			required: "Ce champ est obligatoire",
			email: "Votre email doit avoir le format  nom@domain.com"
		}
	},
	errorPlacement: function(error, element) {

		if (element.attr("name") === "phone_movil_loguin") {

			$(error).addClass("errorLoguinMovil");
		}
		else {
			$(error).addClass("errorLoguinEmail");
		}

		error.insertAfter("#loguin-button");
	}


});
var userenterprise = false;
var enterpriseFormValidate = $("#enterprise-form").validate({
	focusCleanup: true,
	rules: {
		enterprise_code: {
			required: true
		}
	},
	messages: {
		enterprise_code: {
			required: "Ce champ est obligatoire"
		}
	},
	errorPlacement: function(error, element) {


		$(error).addClass("errorLoguinEmail");


		error.insertAfter("#enterprise-loguin");
	}


});

function reservationData() {

	this.conductor = {name: "", last_name: "", address: "", movil_phone: ""};
	this.car = {model: "", plate: "", color: "", mark: ""};
	this.depart = {date: "", hour: "", aeroport: "", company: "", fly_number: "", date_car_in: "", hour_car_in: ""};
	this.arrive = {date: "", hour: "", aeroport: "", company: "", fly_number: "", date_car_out: "", hour_car_out: "", baggage: ""};
	this.reservation = new Array();
	this.setReservation = function(reservation) {

		for (var i = 0; i < reservation.length; i += 2) {

			if (reservation[i] === "date_fly") {

				this.depart.date = reservation[i + 1];
			}
			else if (reservation[i] === "hour_fly") {

				this.depart.hour = reservation[i + 1];
			}
			else if (reservation[i] === "destination") {

				this.depart.aeroport = reservation[i + 1];
			}
			else if (reservation[i] === "company") {

				this.depart.aeroport = reservation[i + 1];
			}
		}

	};
}

function calculateTarif() {

	if (calculateTarifV.form()) {

		var subtotal = getCharge($("#tarifTest1").val(), $("#tarifTest2").val()).charge, total = subtotal - (subtotal * 0.05);
		total = total.toString();
		if (total.indexOf('.') !== -1) {

			total = total.replace(".", ",");
			if ((total.substr(-2).indexOf(',')) === 0)
				total += '0';
		}
		else
			total += ',00';
		//total. = (total.indexOf(",") !== - 1)?',00':
		$("#tarifValue").html("sous-total: <strike>CHF " + subtotal + ",00</strike><br>\n\
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style='color: #e71e26'>rabais -5%</span><br>\n\
total à payer: CHF " + total);
//		TweenMax.fromTo("#tarifValue", 1, {scale: "0"},{left: "-=60px", ease: Back.easeIn});
		TweenMax.fromTo("#tarifValue", 0.5, {scale: 0}, {scale: 1, ease: Back.easeIn});
	}

}

function contactFormValidation() {

	if (contactform.form()) {

		var objectToSend = new Array();
		$(".contact-data-form").each(function() {

			objectToSend.push(Array(this.name, this.value));
		});
		$.ajax({
			type: "POST",
			url: "../phpFiles/index.php",
			data: {type: "contact", data: objectToSend}
		}).done(function(msg) {

			if (parseInt(msg))
			{

				alert('Merci. Votre message a été envoyé.');
			}
			else {

				alert("Désolé, il ya des problèmes, s'il vous plaît essayer à nouveau plus tard. Merci.");
			}

			contactform.reset();
		});
	}

}

function loguinFormValidation() {

	if ($(".errorLoguinEmail").length) {
		$(".errorLoguinEmail").remove();
	}
	if ($(".errorLoguinMovil").length) {
		$(".errorLoguinMovil").remove();
	}

	if (loguinFormValidate.form()) {

		if ($('#phone_movil_loguin').val() === 'mobile...') {

			$('<label for="phone_movil_loguin" class="error errorLoguinMovil">ce n\'est pas un numéro de téléphone</label>').insertAfter('#loguin-button')
		}
		else {
			var objectToSend = new Array();
			$(".loguin-data-form").each(function() {
				if (this.name === 'phone_movil_loguin')
					objectToSend.push(Array('phone_movil', this.value));
				else
					objectToSend.push(Array(this.name, this.value));

			});
			$.ajax({
				dataType: "json",
				type: "POST",
				url: "../phpFiles/index.php",
				data: {type: "loguin", credentials: objectToSend}
			}).done(function(msg) {

				if (msg)
				{

					var fullName = "", fail = false;
					$.each(msg, function(key, val) {

						if (key === "name") {

							fullName = val;
						}
						else if (key === 'last_name') {

							fullName += " " + val;
						}
						else if (key === 'userid') {
							userid = val;
							userConect = val;
						}
						else if (key === 'nouser')
							fail = true;
					});
					if (!fail) {

						window.location.href = "r%C3%A9servation-park.php?userid=" + userid;
						usertweencar.play();
					}
					else {
						$("#wrongUser").css('visibility', 'visible').addClass('error').css('display', '');
					}
				}
				else {

					$("<label for='loguin' class='error errorLoguinEmail'>Les informations d'identification sont incorrectes</label>").insertAfter("#botton_table_header");
				}

			});
		}
	}

}

function enterpriseFormValidation() {

	if ($(".errorLoguinEmail").length) {
		$(".errorLoguinEmail").remove();
	}
	if ($(".errorLoguinMovil").length) {
		$(".errorLoguinMovil").remove();
	}

	if (enterpriseFormValidate.form()) {

		if ($('#enterprise_code').val() === 'code...') {

			$('<label for="phone_movil_loguin" class="error errorLoguinEmail">ce n\'est pas un code</label>').insertAfter('#enterprise-loguin')
		}
		else {
			var objectToSend = new Array();
			$(".enterprice-data-form").each(function() {

				objectToSend.push(Array(this.name, this.value));

			});
			$.ajax({
				dataType: "json",
				type: "POST",
				url: "../phpFiles/index.php",
				data: {type: "loguin-enterprise", credentials: objectToSend}
			}).done(function(msg) {
//$('#main_column').html(msg);
				if (msg)
				{
					for (var value in msg) {
						var fullName = "", fail = false;
						$.each(msg[value], function(key, val) {

							if (key === "name") {

								fullName = val;
							}
							else if (key === 'last_name') {

								fullName += " " + val;
							}
							else if (key === 'userid') {
								userid = val;
								userConect = val;
							}
							else if (key === 'nouser')
								fail = true;
						});
						if (!fail) {

							window.location.href = "reservation-enterprises.php?userid=" + userid;
							usertweencar.play();
						}
						else {
							$("#wrongUser").css('visibility', 'visible').addClass('error').css('display', '');
						}
					}
				}
				else {

					$("<label for='loguin' class='error errorLoguinEmail'>Les informations d'identification sont incorrectes</label>").insertAfter("#botton_table_header");
				}

			});
		}
	}
}

var userid = false, userConect = false, idcar = false;

function userFormValidation() {

	if (userform.form()) {

		var objectToSend = new Array();

		$(".user-data-form").each(function() {

			objectToSend.push(Array(this.name, this.value));
		});

		$.ajax({
			dataType: "json",
			type: "POST",
			url: "../phpFiles/index.php",
			data: {type: "insert", user: objectToSend}
		}).done(function(msg) {

			if (msg)
			{

				var fullName = "", name = "", sex = "", conductorid = "", fail = false;
				$.each(msg, function(key, val) {

					if (key === "name") {

						name = val;
					}
					else if (key === 'last_name') {

						fullName += name + " " + val;
					}
					else if (key === 'sex') {

						sex = val;
					}
					else if (key === 'email') {

						$("#userEmail").val(val);
					}
					else if (key === 'conductorid') {

						conductorid = val;
					}
					else if (key === 'fail') {

						fail = true;
					}
					else {
						userid = val;
						userConect = val;
					}
				});
				if (!fail) {
					$("#div-loguin-form").replaceWith('<label style="float: right; text-align: right; margin-right: 30px;color: #005599; font-size: 1.2em; z-index: 999">Bievenue ' + sex + ' ' + name + '<a href="" onmousedown="logout()"> déconnexion</a></label>');
					$("<option value='" + conductorid + "' selected>" + sex + ' ' + name + "</option>").appendTo("#conductor_name");
					usertweencar.play();
				}
				else {
					alert("Oups .. un problème, s'il vous plaît réessayer plus tard. Merci.");
				}
			}

		});

	}

}

var reservation = new Array(), car = new Array(), conductor = new Array();
function reservationFormValidation() {

	if (carForm.form() && reservationForm.form()) {

		reservation = new Array();
		car = new Array();
		conductor = $(".conductor-select-form").val();
		var dataConfirm = new reservationData();

		$.ajax({
			dataType: "json",
			async: false,
			type: "POST",
			url: "../phpFiles/index.php",
			data: {type: "get", conductor: conductor}
		}).done(function(msg) {

			if (msg)
			{

				$.each(msg, function(key, val) {

					dataConfirm.reservation[ key ] = val;
				});
			}

		});
		if ($('#carSelect').length > 0) {

			car = $('#carSelect').val();
			$.ajax({
				dataType: "json",
				async: false,
				type: "POST",
				url: "../phpFiles/index.php",
				data: {type: "get", car: car}
			}).done(function(msg) {

				if (msg)
				{

					$.each(msg, function(key, val) {

						dataConfirm.reservation[ key ] = val;
					});
				}

			});
		}
		else {

			$(".car-data-form").each(function() {

				if (this.name !== 'carSelect') {

					car.push(Array(this.name, this.value));
					dataConfirm.reservation[ this.name ] = this.value;
				}

			});
		}

		$(".reservation-data-form").each(function() {

			reservation.push(Array(this.name, this.value));
			if (this.name === 'conductor')
				dataConfirm.reservation[ this.name ] = dataConfirm.reservation[ 'sex' ] + '. ' + this.value;
			else
				dataConfirm.reservation[ this.name ] = this.value;
		});
		reservation.push(Array('baggage', $("[name='baggage']:checked").val()));
		dataConfirm.reservation[ 'baggage' ] = $("[name='baggage']:checked").val();
		dataConfirm.reservation[ 'emailConfirm' ] = $("#userEmail").val();
		var charge = getCharge(dataConfirm.reservation[ 'day_date_car_in' ], dataConfirm.reservation[ 'day_date_car_out' ]);
		if (charge) {

			var serviceCharge = 0;
			if ((typeof $("input[name='washing']:checked").val() !== "undefined")) {

				reservation.push(Array("washing", $("input[name='washing']:checked").attr('id')));
				serviceCharge += parseInt($("input[name='washing']:checked").val());
				if ($("#service1").length)
					$("#service1").replaceWith('<tr id="service1"><td><label class="displayContentConfirm" style="width: 10px" >1</label></td><td style="width: 200px"><label class="displayContentConfirm" style="width: 300px;" >Lavage a la main: extérieur</label></td><td></td><td><label class="displayContentConfirm"><strong>CHF</strong></label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right"><strong>' + $("input[name='washing']:checked").val() + ',00</strong></label></td></tr>');
				else
					$('<tr id="service1"><td><label class="displayContentConfirm" style="width: 10px" >1</label></td><td style="width: 200px"><label class="displayContentConfirm" style="width: 300px;" >Lavage a la main: extérieur</label></td><td></td><td><label class="displayContentConfirm"><strong>CHF</strong></label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right"><strong>' + $("input[name='washing']:checked").val() + ',00</strong></label></td></tr>').insertBefore("#serviceMark");
			}
			else {
				if ($("#service1").length)
					$("#service1").replaceWith('');
			}
			if ((typeof $("input[name='aspirate']:checked").val() !== "undefined")) {

				reservation.push(Array("aspirate", $("input[name='aspirate']:checked").attr('id')));
				serviceCharge += parseInt($("input[name='aspirate']:checked").val());
				if ($("#service2").length)
					$("#service2").replaceWith('<tr id="service2"><td><label class="displayContentConfirm" style="width: 10px" >1</label></td><td style="width: 200px"><label class="displayContentConfirm" style="width: 300px;" >Aspirateur</label></td><td></td><td><label class="displayContentConfirm"><strong>CHF</strong></label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right"><strong>' + $("input[name='aspirate']:checked").val() + ',00</strong></label></td></tr>');
				else
					$('<tr id="service2"><td><label class="displayContentConfirm" style="width: 10px" >1</label></td><td style="width: 200px"><label class="displayContentConfirm" style="width: 300px;" >Aspirateur</label></td><td></td><td><label class="displayContentConfirm"><strong>CHF</strong></label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right"><strong>' + $("input[name='aspirate']:checked").val() + ',00</strong></label></td></tr>').insertBefore("#serviceMark");
			}
			else {
				if ($("#service2").length)
					$("#service2").replaceWith('');
			}

			var total = parseInt(charge.charge + serviceCharge), tarifV = parseFloat(charge.charge - 25);
			reservation.push(Array('charge', total, 'days_car_in', charge.days));
			reservation.push(Array('days_car_in', charge.days));
			dataConfirm.reservation[ 'charge' ] = '<label class="displayContentConfirm">CHF</label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right">' + tarifV + ',00</label>';
			dataConfirm.reservation[ 'days' ] = charge.days;
			dataConfirm.reservation[ 'total' ] = '<label class="displayContentConfirm"><strong>CHF</strong></label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right"><strong>' + total + ',00</strong></label>';
			$(".confirm-data-reservation").each(function() {

				if (this.id === "day_date_car_in") {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + " " + dataConfirm.reservation[ 'hour_car_in' ] + "</strong>");
				}
				else if (this.id === "date_fly") {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + " " + dataConfirm.reservation[ 'hour_fly' ] + "</strong>");
				}
				else if (this.id === "day_date_car_out") {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + " " + dataConfirm.reservation[ 'hour_car_out' ] + "</strong>");
				}
				else if (this.id === "date_fly_back") {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + " " + dataConfirm.reservation[ 'hour_fly_back' ] + "</strong>");
				}
				else if (this.id === "phone_movil2") {

					$(this).html("Mobile: <strong>" + dataConfirm.reservation[ "phone_movil" ] + "</strong>");
				}
				else if (this.id === "emailConfirm") {

					$(this).html("Email: <strong>" + dataConfirm.reservation[ this.id ] + "</strong>");
				}
				else if (this.id === "days") {

					$(this).html(dataConfirm.reservation[ this.id ]);
				}
				else if (this.id === "sex") {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + ".</strong>");
				}
				else if (this.id === "address") {

					$(this).html("Adresses (Rue et No): <strong>" + dataConfirm.reservation[ this.id ] + "</strong>");
				}
				else if (this.id === "postal_code") {

					$(this).html("C.P/localité: <strong>" + dataConfirm.reservation[ this.id ] + "</strong>");
				}
				else {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + "</strong>");
				}


			});
			reservationtweenConfirm.play();
			TweenLite.to(window, 3, {scrollTo: {y: 0}, ease: Power2.easeOut, delay: 2});
		}
		else {

			alert("Les dates sont incorrects.");
		}

	}
}

function reservationEnterprisesFormValidation() {

	if (conductorForm.form() && carForm.form() && reservationForm.form()) {

		objectToSend = new Array();
		dataToSend = false;
		reservation = new Array();

		var dataConfirm = new reservationData();

		if (conductorReserva)
		{
			$(".conductor-data-form").each(function() {

				if (conductorReserva[this.name] !== this.value)
					objectToSend.push(Array(this.name, this.value));
			});
			if (objectToSend.length) {
				conductor = conductorReserva['conductorid'];
				objectToSend.push(Array('conductorid', conductorReserva['conductorid']));
				dataToSend = {type: 'updateConductor', conductor: objectToSend};
			}

		}
		else {
			$(".conductor-data-form").each(function() {

				objectToSend.push(Array(this.name, this.value));
			});
			dataToSend = {type: 'insert', conductor: objectToSend, enterprise: true};
		}
		if (dataToSend) {
			$.ajax({
				dataType: "json",
				async: false,
				type: "POST",
				url: "../phpFiles/index.php",
				data: dataToSend
			}).done(function(msg) {

				if (msg)
				{
					conductor = msg['conductorid'];
					$.each(msg, function(key, val) {

						dataConfirm.reservation[ key ] = val;
					});
					dataConfirm.reservation[ 'conductor' ] = msg[ 'sex' ] + '. ' + msg[ 'name' ] + ' ' + msg[ 'last_name' ];
				}

			});
		}
		else {
			conductor = conductorReserva['conductorid'];
			dataConfirm.reservation[ "sex" ] = conductorReserva[ "sex" ];
			dataConfirm.reservation[ "name" ] = conductorReserva[ "name" ];
			dataConfirm.reservation[ "last_name" ] = conductorReserva[ "last_name" ];
			dataConfirm.reservation[ "postal_code" ] = conductorReserva[ "postal_code" ];
			dataConfirm.reservation[ "address" ] = conductorReserva[ "address" ];
			dataConfirm.reservation[ "phone_movil" ] = conductorReserva[ "phone_movil" ];
			dataConfirm.reservation[ 'conductor' ] = conductorReserva[ 'sex' ] + '. ' + conductorReserva[ 'name' ] + ' ' + conductorReserva[ 'last_name' ];
		}

		objectToSend = new Array();
		dataToSend = false;

		if (carReserva)
		{
			$(".car-data-form").each(function() {

				if (carReserva[this.name] !== this.value)
					objectToSend.push(Array(this.name, this.value));
			});
			if (objectToSend.length) {
				car = carReserva['idcar'];
				objectToSend.push(Array('idcar', carReserva['idcar']));
				dataToSend = {type: 'updateCar', car: objectToSend};
			}

		}
		else {
			$(".car-data-form").each(function() {

				objectToSend.push(Array(this.name, this.value));
			});
			dataToSend = {type: 'insert', car: objectToSend, enterprise: true};
		}
		if (dataToSend) {
			$.ajax({
				dataType: "json",
				async: false,
				type: "POST",
				url: "../phpFiles/index.php",
				data: dataToSend
			}).done(function(msg) {

				if (msg)
				{
					car = carReserva['idcar'];
					$.each(msg, function(key, val) {

						dataConfirm.reservation[ key ] = val;
					});
				}

			});
		}
		else {
			car = carReserva['idcar'];
			dataConfirm.reservation[ "mark" ] = carReserva[ "mark" ];
			dataConfirm.reservation[ "model" ] = carReserva[ "model" ];
			dataConfirm.reservation[ "plate" ] = carReserva[ "plate" ];
			dataConfirm.reservation[ "color" ] = carReserva[ "color" ];

		}

		$(".reservation-data-form").each(function() {

			reservation.push(Array(this.name, this.value));

			dataConfirm.reservation[ this.name ] = this.value;
		});
		reservation.push(Array('baggage', $("[name='baggage']:checked").val()));
		dataConfirm.reservation[ 'baggage' ] = $("[name='baggage']:checked").val();
		dataConfirm.reservation[ 'emailConfirm' ] = $("#userEmail").val();
		var charge = getCharge(dataConfirm.reservation[ 'day_date_car_in' ], dataConfirm.reservation[ 'day_date_car_out' ]);
		if (charge) {

			var serviceCharge = 0;
			if ((typeof $("input[name='washing']:checked").val() !== "undefined")) {

				reservation.push(Array("washing", $("input[name='washing']:checked").attr('id')));
				serviceCharge += parseInt($("input[name='washing']:checked").val());
				if ($("#service1").length)
					$("#service1").replaceWith('<tr id="service1"><td><label class="displayContentConfirm" style="width: 10px" >1</label></td><td style="width: 200px"><label class="displayContentConfirm" style="width: 300px;" >Lavage a la main: extérieur</label></td><td></td><td><label class="displayContentConfirm"><strong>CHF</strong></label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right"><strong>' + $("input[name='washing']:checked").val() + ',00</strong></label></td></tr>');
				else
					$('<tr id="service1"><td><label class="displayContentConfirm" style="width: 10px" >1</label></td><td style="width: 200px"><label class="displayContentConfirm" style="width: 300px;" >Lavage a la main: extérieur</label></td><td></td><td><label class="displayContentConfirm"><strong>CHF</strong></label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right"><strong>' + $("input[name='washing']:checked").val() + ',00</strong></label></td></tr>').insertBefore("#serviceMark");
			}
			else {
				if ($("#service1").length)
					$("#service1").replaceWith('');
			}
			if ((typeof $("input[name='aspirate']:checked").val() !== "undefined")) {

				reservation.push(Array("aspirate", $("input[name='aspirate']:checked").attr('id')));
				serviceCharge += parseInt($("input[name='aspirate']:checked").val());
				if ($("#service2").length)
					$("#service2").replaceWith('<tr id="service2"><td><label class="displayContentConfirm" style="width: 10px" >1</label></td><td style="width: 200px"><label class="displayContentConfirm" style="width: 300px;" >Aspirateur</label></td><td></td><td><label class="displayContentConfirm"><strong>CHF</strong></label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right"><strong>' + $("input[name='aspirate']:checked").val() + ',00</strong></label></td></tr>');
				else
					$('<tr id="service2"><td><label class="displayContentConfirm" style="width: 10px" >1</label></td><td style="width: 200px"><label class="displayContentConfirm" style="width: 300px;" >Aspirateur</label></td><td></td><td><label class="displayContentConfirm"><strong>CHF</strong></label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right"><strong>' + $("input[name='aspirate']:checked").val() + ',00</strong></label></td></tr>').insertBefore("#serviceMark");
			}
			else {
				if ($("#service2").length)
					$("#service2").replaceWith('');
			}

			var total = parseInt(charge.charge + serviceCharge), tarifV = parseFloat(charge.charge - 25);
			reservation.push(Array('charge', total, 'days_car_in', charge.days));
			reservation.push(Array('days_car_in', charge.days));

			dataConfirm.reservation[ 'charge' ] = '<label class="displayContentConfirm">CHF</label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right">' + tarifV + ',00</label>';
			dataConfirm.reservation[ 'days' ] = charge.days;
			dataConfirm.reservation[ 'total' ] = '<label class="displayContentConfirm"><strong>CHF</strong></label><label class="displayContentConfirm" style="width: 40px; text-align: right; margin-right: 10px; float: right"><strong>' + total + ',00</strong></label>';
			$(".confirm-data-reservation").each(function() {

				if (this.id === "day_date_car_in") {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + " " + dataConfirm.reservation[ 'hour_car_in' ] + "</strong>");
				}
				else if (this.id === "date_fly") {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + " " + dataConfirm.reservation[ 'hour_fly' ] + "</strong>");
				}
				else if (this.id === "day_date_car_out") {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + " " + dataConfirm.reservation[ 'hour_car_out' ] + "</strong>");
				}
				else if (this.id === "date_fly_back") {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + " " + dataConfirm.reservation[ 'hour_fly_back' ] + "</strong>");
				}
				else if (this.id === "phone_movil2") {

					$(this).html("Mobile: <strong>" + dataConfirm.reservation[ "phone_movil" ] + "</strong>");
				}
//				else if (this.id === "emailConfirm") {
//
//					$(this).html("Email: <strong>" + dataConfirm.reservation[ this.id ] + "</strong>");
//				}
				else if (this.id === "days") {

					$(this).html(dataConfirm.reservation[ this.id ]);
				}
				else if (this.id === "sex") {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + ".</strong>");
				}
				else if (this.id === "address") {

					$(this).html("Adresses (Rue et No): <strong>" + dataConfirm.reservation[ this.id ] + "</strong>");
				}
				else if (this.id === "postal_code") {

					$(this).html("C.P/localité: <strong>" + dataConfirm.reservation[ this.id ] + "</strong>");
				}
				else {

					$(this).html("<strong>" + dataConfirm.reservation[ this.id ] + "</strong>");
				}


			});
			reservationtweenConfirm.play();
			TweenLite.to(window, 3, {scrollTo: {y: 0, x: 0}, ease: Power2.easeOut, delay: 2});
		}
		else {

			alert("Les dates sont incorrects.");
		}

	}
}

function sendReservation() {

	$.ajax({
		type: "POST",
		url: "../phpFiles/index.php",
		data: {type: 'insert', reservation: reservation, car: car, conductor: conductor, userid: userReserva['userid']}
	}).done(function(msg) {
		if (msg)
		{
			reservationtweenConfirmFinal.play();
		}

	});
}

function showConductorForm() {

	$("#conductor-form").each(function() {
//this.reset();
	});
	//$("#div-conductor").css("border", "solid 4px #e71e26");
	TweenMax.to("#div-conductor", 1, {css: {height: 367}});
}

function showCarForm() {

	$("#add-car-form").each(function() {
//this.reset();
	});
	//$("#div-car").css("border", "solid 4px #e71e26");
	TweenMax.to("#div-car", 1, {css: {height: 245}});

}

function addConductor() {

	if (conductorForm.form()) {

		var conductor = new Array();
		$(".conductor-data-form").each(function() {

			conductor.push(Array(this.name, this.value));
		});
		$.ajax({
			dataType: "json",
			type: "POST",
			url: "../phpFiles/index.php",
			data: {type: 'insert', conductor: conductor}
		}).done(function(msg) {

			if (msg)
			{
				var fullName = "", conductorid = "", fail = false;
				$.each(msg, function(key, val) {

					if (key === "name") {

						fullName = val;
					}
					else if (key === "last_name") {

						fullName += " " + val;
					}
					else if (key === "conductorid") {

						conductorid = val;
					}
					else if (key === "fail") {

						alert("Sorry, there are some error. Please try later.")
					}
				});
				if (!fail) {

					$("<option value='" + conductorid + "' selected>" + fullName + "</option>").appendTo("#conductor_name");
					TweenMax.to("#div-conductor", 1, {css: {height: 0}});
					return true;
				}


			}

		});
	}
	return false;
}

function addCar() {

	if (addCarForm.form()) {

		var car = new Array();
		$(".add-car-data-form").each(function() {

			car.push(Array(this.name, this.value));
		});
		$.ajax({
			dataType: "json",
			type: "POST",
			url: "../phpFiles/index.php",
			data: {type: 'insert', car: car}
		}).done(function(msg) {

			if (msg)
			{
				var mark = "", carid = "", fail = false;
				$.each(msg, function(key, val) {

					if (key === "mark") {

						mark = val;
					}
					else if (key === "carid") {

						carid = val;
					}
					else if (key === "fail") {

						alert("Sorry, there are some error. Please try later.")
					}
				});
				if (!fail) {

					$("<option value='" + carid + "' selected>" + mark + "</option>").appendTo("#carSelect");
					TweenMax.to("#div-car", 1, {css: {height: 0}});
					return true;
				}


			}

		});
	}
	return false;
}

function logout() {

	$.ajax({
		type: "POST",
		url: "../phpFiles/index.php",
		data: {type: 'logout'}
	}).done(function(msg) {

		if (msg)
		{

		}

	});
}

function getCharge(carIn, carOut) {

	var dayCarIn = parseInt(carIn.substr(0, 2)),
			dayCarOut = parseInt(carOut.substr(0, 2)),
			monthCarIn = parseInt(carIn.substr(3, 2)),
			monthCarOut = parseInt(carOut.substr(3, 2)),
			yearCarIn = parseInt(carIn.substr(6, 4)),
			yearCarOut = parseInt(carOut.substr(6, 4)),
			totalDaysIn = 0;
	if (dayCarIn < dayCarOut && monthCarIn === monthCarOut) {

		totalDaysIn = dayCarOut - dayCarIn;
	}
	else if ((monthCarIn < monthCarOut)) {

		for (var month = monthCarIn; month < monthCarOut; month++) {

			if (month % 2 === 0 && month < 8 && month !== 2) {
				if (month === monthCarIn)
					totalDaysIn = (30 - dayCarIn);
				else
					totalDaysIn += 30;
			}
			else if (month % 2 === 0 && month >= 8 && month !== 2) {
				if (month === monthCarIn)
					totalDaysIn = (31 - dayCarIn);
				else
					totalDaysIn += 31;
			}
			else if (month % 2 !== 0 && month < 8 && month !== 2) {
				if (month === monthCarIn)
					totalDaysIn = (31 - dayCarIn);
				else
					totalDaysIn += 31;
			}
			else if (month % 2 !== 0 && month >= 8 && month !== 2) {
				if (month === monthCarIn)
					totalDaysIn = (30 - dayCarIn);
				else
					totalDaysIn += 30;
			}
			else {

				if (month === monthCarIn)
					totalDaysIn += (28 - dayCarIn);
				else
					totalDaysIn += 28;
			}
		}
		totalDaysIn += dayCarOut;
	}
	else if ((yearCarIn < yearCarOut)) {

		for (var month = monthCarIn; month !== monthCarOut; month++) {

			if (month % 2 === 0 && month < 8 && month !== 2) {
				if (month === monthCarIn)
					totalDaysIn = (30 - dayCarIn);
				else
					totalDaysIn += 30;
			}
			else if (month % 2 === 0 && month >= 8 && month !== 2) {
				if (month === monthCarIn)
					totalDaysIn = (31 - dayCarIn);
				else
					totalDaysIn += 31;
			}
			else if (month % 2 !== 0 && month < 8 && month !== 2) {
				if (month === monthCarIn)
					totalDaysIn = (31 - dayCarIn);
				else
					totalDaysIn += 31;
			}
			else if (month % 2 !== 0 && month >= 8 && month !== 2) {
				if (month === monthCarIn)
					totalDaysIn = (30 - dayCarIn);
				else
					totalDaysIn += 30;
			}
			else {
				if (month === monthCarIn)
					totalDaysIn += (28 - dayCarIn);
				else
					totalDaysIn += 28;
			}
			if (month === 12)
				month = 0;
		}
		totalDaysIn += dayCarOut;
	}

	if (totalDaysIn || (dayCarIn === dayCarOut)) {
		totalDaysIn++;
		var aux = 0;
		for (var i = 1; i <= totalDaysIn; i++) {

			aux += (i <= 3) ? 15 : 10;
		}

		return {charge: parseInt(aux + 25), days: parseInt(totalDaysIn)};
	}
	return false;
}

function userEnterpriseFormValidation() {

	if (userform.form()) {

		var objectToSend = new Array(), fail = false;
		if (userenterprise) {
			$(".user-data-form").each(function() {

				if (userenterprise[this.name] !== this.value)
				{
					objectToSend.push(Array(this.name, this.value));
				}
			});
			if (objectToSend.length) {

				objectToSend.push(Array('userid', userenterprise['userid']));
				dataToSend = {type: 'updateUser', user: objectToSend};

			}
		}
		else {
			$(".user-data-form").each(function() {

				objectToSend.push(Array(this.name, this.value));
			});
			dataToSend = {type: 'insert', user: objectToSend};
		}
		if (typeof (dataToSend) !== 'undefined') {
			$.ajax({
				dataType: "json",
				type: "POST",
				url: "../phpFiles/index.php",
				data: dataToSend
			}).done(function(msg) {

				if (msg)
				{
					
					if (typeof (msg['namec']) !== 'undefined') {
						$('#conductor_name').append('<option value="' + msg['conductorid'] + '" >' + msg['sexc'] + ' ' + msg['namec'] + ' ' + msg['last_namec'] + '</option>');
						console.log(msg['sexc'] + ' ' + msg['namec'] + ' ' + msg['last_namec'] );
						if (conductorsData) {
							conductorsData.push({
								"conductorid": msg['conductorid'],
								"sex": msg['sexc'],
								"name": msg['namec'],
								"last_name": msg['last_namec'],
								"postal_code": msg['postal_codec'],
								"address": msg['addressc'],
								"phone_movil": msg['phone_movilc']
							});
						}
						else {
							
							conductorsData = [{
								"conductorid": msg['conductorid'],
								"sex": msg['sexc'],
								"name": msg['namec'],
								"last_name": msg['last_namec'],
								"postal_code": msg['postal_codec'],
								"address": msg['addressc'],
								"phone_movil": msg['phone_movilc']
							}];
						}
					}
					userReserva = msg;
					var fullName = "", name = "", sex = "", conductorid = "";
					$.each(msg, function(key, val) {

						if (key === "name") {

							name = val;
						}
						else if (key === 'last_name') {

							fullName += name + " " + val;
						}
						else if (key === 'sex') {

							sex = val;
						}
						else if (key === 'email') {

							$("#userEmail").val(val);
						}
						else if (key === 'conductorid') {

							conductorid = val;
						}
						else if (key === 'fail') {

							fail = true;
						}
//						else {
//							userid = val;
//							userConect = val;
//						}
					});

				}

			});
		}
		else {
			userReserva = userenterprise;

		}

		if (!fail) {
			$("#div-loguin-form").replaceWith('<label style="float: right; text-align: right; margin-right: 30px;color: #005599; font-size: 1.2em; z-index: 999">Bievenue ' + sex + ' ' + name + '<a href="" onmousedown="logout()"> déconnexion</a></label>');
			//$("<option value='" + conductorid + "' selected>" + sex + ' ' + name + "</option>").appendTo("#conductor_name");
			usertweencarenterprise.play();

		}
		else {
			alert("Oups .. un problème, s'il vous plaît réessayer plus tard. Merci.");
		}

	}

}

function getUserById(userid) {

	$.ajax({
		dataType: "json",
		type: "POST",
		url: "../phpFiles/index.php",
		data: {type: "getUserById", user: userid}
	}).done(function(msg) {

		if (msg)
		{
			userenterprise = msg;

			$.each(msg, function(key, val) {

				if (key === "name") {

					$('#name').val(val);
				}
				else if (key === 'last_name') {

					$('#last_name').val(val);
				}
				else if (key === 'sex') {

					$('#sex').val(val);
				}
				else if (key === 'email') {

					$("#cemail").val(val);
				}
				else if (key === 'address') {

					$("#address").val(val);
				}
				else if (key === 'postal_code') {

					$("#postal_code").val(val);
				}
				else if (key === 'country') {

					$("#country").val(val);
				}
				else if (key === 'phone_movil') {

					$("#phone_movil").val(val);
				}
				else if (key === 'phone_home') {

					$("#phone_home").val(val);
				}
				else if (key === 'fax') {

					$("#fax").val(val);
				}
				else if (key === 'fail') {

					fail = true;
				}
				else {
					userid = val;
					userConect = val;
				}
			});
//				if (!fail) {
//					$("#div-loguin-form").replaceWith('<label style="float: right; text-align: right; margin-right: 30px;color: #005599; font-size: 1.2em; z-index: 999">Bievenue ' + sex + ' ' + name + '<a href="" onmousedown="logout()"> déconnexion</a></label>');
//					$("<option value='" + conductorid + "' selected>" + sex + ' ' + name + "</option>").appendTo("#conductor_name");
//					usertweencar.play();
//				}
//				else {
//					alert("Oups .. un problème, s'il vous plaît réessayer plus tard. Merci.");
//				}
		}

	});

}

function setConductorData() {


}
var datesFields = new Array();
function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	}
}

$(document).ready(function() {
	$(".date-france").each(function() {

		datesFields[ this.id ] = $(this).datepicker({
			monthNames: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
			dayNames: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"],
			dayNamesShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"],
			dayNamesMin: ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"],
			nextText: "next",
			prevText: "préc",
			minDate: new Date(),
			dateFormat: "dd/mm/yy",
			onSelect: function(date) {
				if (this.id === "date_fly") {
					datesFields[ "date_fly_back" ].datepicker("option", "minDate", date);
				}
				else if (this.id === "day_date_car_in") {
					datesFields[ "day_date_car_out" ].datepicker("option", "minDate", date);
				}
				else if (this.id === "tarifTest1") {
					datesFields[ "tarifTest2" ].datepicker("option", "minDate", date);
				}

			}
		});
	});
	if ($("#bannerLink1").length) {

		$("#abannerLink1").css("color", "#ffffff").css("background", "#e71e26");
	}
	else if ($("#bannerLink2").length) {

		$("#abannerLink2").css("color", "#ffffff").css("background", "#e71e26");
	}
	else if ($("#bannerLink3").length) {

		$("#abannerLink3").css("color", "#ffffff").css("background", "#e71e26");
	}
	else if ($("#bannerLink4").length) {

		$("#abannerLink4").css("color", "#ffffff").css("background", "#e71e26");
	}
	else if ($("#bannerLink5").length) {

		$("#abannerLink5").css("color", "#ffffff").css("background", "#e71e26");
	}
	else if ($("#bannerLink6").length) {

		$("#abannerLink6").css("color", "#ffffff").css("background", "#e71e26");
	}

	$("input[type='radio']").click(function()
	{
		var previousValue = $(this).attr('previousValue');
		var name = $(this).attr('name');
		if (previousValue == 'checked')
		{
			$(this).removeAttr('checked');
			$(this).attr('previousValue', false);
		}
		else
		{
			$("input[name=" + name + "]:radio").attr('previousValue', false);
			$(this).attr('previousValue', 'checked');
		}
	});

});


